<template>
  <div class="Login">
    <head-title>登录</head-title>
    <logo></logo>
    <van-field
      v-model="username"
      label="用户名"
      placeholder="请输入用户名"
      @input="checkUsername"
      :error-message="usernameErrMsg"
    />
    <van-field
      v-model="password"
      type="password"
      label="密码"
      @input="checkPassword"
      :error-message="passwordErrMsg"
    />
    <shop-button @click.native="login">登录</shop-button>
    <router-link to="/register">没有账号？去注册</router-link>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
      usernameErrMsg: "",
      passwordErrMsg: "",
    };
  },
  created() {
    const { username, password } = this.$route.params;
    if (username != "" && password != "") {
      this.username = username;
      this.password = password;
    }
  },
  methods: {
    checkUsername() {
      if (this.username == "") {
        this.usernameErrMsg = "";
      } else {
        const reg = /^\d{3,12}$/;
        if (reg.test(this.username)) {
          this.usernameErrMsg = "";
        } else {
          this.usernameErrMsg = "用户名格式错误";
        }
      }
    },
    checkPassword() {
      if (this.password == "") {
        this.passwordErrMsg = "";
      } else {
        const reg = /^[a-z0-9]{3,12}$/;
        if (reg.test(this.password)) {
          this.passwordErrMsg = "";
        } else {
          this.passwordErrMsg = "密码格式错误";
        }
      }
    },
    async login() {
      if (
        this.password != "" &&
        this.username != "" &&
        this.usernameErrMsg == "" &&
        this.passwordErrMsg == ""
      ) {
        const res = await this.$axios.post("/login", {
          username: this.username,
          password: this.password,
        });
        console.log(res.data);

        const { message, statusCode, data } = res.data;
        if (statusCode == 200) {
          console.log(this.$route);
          this.$toast.success(message);
          localStorage.setItem("token", data.token);
          localStorage.setItem("id", data.user.id);
          if (this.$route.params.back) {
            this.$router.back();
          } else {
            this.$router.push("/user");
          }
        } else {
          this.$toast.fail(message);
        }
      } else {
        this.$toast.fail("登录信息错误");
      }
    },
  },
};
</script>

<style>
</style>